from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from areas.models import Area


class AreasView(View):
    def get(self, request):
        area_id = request.GET.get('area_id')

        if not area_id:
            province_list = cache.get('province_list')

            if province_list:
                res = {
                    'code': 0,
                    'errmsg': 'OK',
                    'province_list': province_list
                }
                return JsonResponse(res)

            else:
                provinces = Area.objects.filter(parent__isnull=True)

                province_list = []

                for prov in provinces:
                    prov_data = {
                        'id': prov.id,
                        'name': prov.name
                    }
                    province_list.append(prov_data)

                cache.set('province_list', province_list, 3600 * 24 * 14)

                res = {
                    'code': 0,
                    'errmsg': 'OK',
                    'province_list': province_list
                }
                return JsonResponse(res)

        else:
            try:
                area = Area.objects.get(id=area_id)
            except Exception:
                return JsonResponse({'code': 9999, 'errmsg': 'error ID'})

            subs_list = cache.get('subs_list_%s' % area_id)

            if subs_list:
                res = {
                    'code': 0,
                    'errmsg': 'OK',
                    'sub_data': {
                        'id': area.id,
                        'name': area.name,
                        'subs': subs_list
                    }
                }
                return JsonResponse(res)

            else:
                subs = area.subs.all()

                subs_list = []

                for sub in subs:

                    sub_data = {
                        'id': sub.id,
                        'name': sub.name
                    }
                    subs_list.append(sub_data)

                cache.set('subs_list_%s' % area_id, subs_list, 3600 * 24 * 14)

                res = {
                    'code': 0,
                    'errmsg': 'OK',
                    'sub_data': {
                        'id': area.id,
                        'name': area.name,
                        'subs': subs_list
                    }
                }
                return JsonResponse(res)

